
import * as React from 'react';
import {runOnJS} from 'react-native-reanimated';

import {
    StyleSheet,
    View,
    Text,
    Dimensions,
    TouchableWithoutFeedback,
    TouchableOpacity,
    Platform,
    Image,
    ImageBackground,
} from 'react-native';
import {
    useCameraDevices,
    useFrameProcessor,
    CameraDeviceFormat, sortFormats,
} from 'react-native-vision-camera';

import {Camera} from 'react-native-vision-camera';
import {scanFaces, Face} from 'vision-camera-face-detector';
import {SafeAreaView} from 'react-native-safe-area-context';
import AllStyle from '../../../../style';
import {BottomButton} from '../../../../componet/settingComponent/BottomButton';
import {Toast} from '../../../../utils/Toast';
import {Loading} from '../../../../utils/Loading';
import {useMemo, useRef} from 'react';
import {upload} from '../../../../api/upload';
import {saveFaceDatabase} from '../../../../api/facedatabase';

let faceWidthAndHeight = 220;
if (Platform.OS === 'ios') {
    faceWidthAndHeight = 220;
}
if (Platform.OS === 'android') {
    faceWidthAndHeight = 240;
}
const width = Dimensions.get('window').width;

export function FaceDetection(props) {
    const [userId, setUserId] = React.useState(props.route.params.userId == null ? null : props.route.params.userId);
    //const []=React.useState(props.route.params.userId==null?null:props.route.params.userId)
    const [hasPermission, setHasPermission] = React.useState(false);
    const [faces, setFaces] = React.useState([]);
    const [msg, setMsg] = React.useState(null);
    const [uploadMsg, setUploadMsg] = React.useState('人脸图像录入中');
    const [isActiveVal, setIsActiveVal] = React.useState(true);
    const [photoPath, setPhotoPath] = React.useState(null);
    const camara = useRef(null);
    const devices = useCameraDevices();
    const device = devices.front;
    // const formats = useMemo<CameraDeviceFormat>(() => {
    //     if (device?.formats == null) return [];
    //     return device.formats.sort(sortFormats);
    // }, [device?.formats]);


    React.useEffect(() => {
        let facesArr = [];
        facesArr = faces;
        if (facesArr.length > 0) {
            let face = facesArr[0];
            if (JSON.stringify(face.contours) == '{}') {
                setMsg('人脸信息不全');
            } else {
                if (face.leftEyeOpenProbability == 1 && face.rightEyeOpenProbability == 1 && face.pitchAngle == 0 && face.rollAngle == 0) {
                    setMsg('面部遮挡');
                } else {
                    if (face.leftEyeOpenProbability < 0.7 && face.rightEyeOpenProbability < 0.7) {
                        setMsg('请睁眼');
                    } else {
                        if (!(Math.abs(face.pitchAngle) < 6 && Math.abs(face.rollAngle) < 6 && Math.abs(face.yawAngle) <= 6)) {
                            setMsg('请正面朝向屏幕');
                        } else {
                            setIsActiveVal(false);
                            takePicture().then(res => {
                                //console.log('成功',res)
                            });


                        }
                    }
                }
            }
        }


    }, [faces]);

    React.useEffect(() => {
        (async () => {
            const status = await Camera.requestCameraPermission();
            setHasPermission(status === 'authorized');
        })();
    }, []);

    const frameProcessor = useFrameProcessor((frame) => {
        'worklet';
        const scannedFaces = scanFaces(frame);
        //console.log(setFaces,'setFaces')
        runOnJS(setFaces)(scannedFaces);
    }, []);


    const back = () => {
        //console.log(JSON.stringify(props));
        const route = {
            name: props.route.params.routePathName,
            params: {
                title: '人脸录入',
            },
        };
        props.navigation.navigate(route);
    };
    const goto = (name, params) => {

        const route = {
            name: name,
            params: {
                //routePathName: props.route.name,
                ...params,
            },

        };
        props.navigation.navigate(route);
    };
    const takePicture = async () => {
        if (camara.current) {
            let photo = null;
            if (Platform.OS === 'ios') {
                photo = await camara.current.takePhoto({
                    qualityPrioritization: 'speed',
                    flash: 'off',
                    enableAutoRedEyeReduction: true,
                });
            } else {
                photo = await camara.current.takeSnapshot({
                    quality: 80,
                    skipMetadata: true,
                });
            }


            //alert(photo.path)
            setMsg(null);
            setUploadMsg('上传中');
            setPhotoPath(`file://` + photo.path);
            setTimeout(() => {
                setUploadMsg('上传成功');
            }, 2000);


            // console.log('photo',photo)
        }


    };
    const reEntry = () => {
        setIsActiveVal(true);
        setUploadMsg('人脸图像录入中');
    };
    const complete = () => {
        const data = new FormData();
        //console.log(photoPath,"photoPath")
        data.append('file', {
            // uri: 'file:///data/user/0/com.frasreactnative/cache/mrousavy1395594957.jpg',
            uri: photoPath,
            type: 'image/jpeg',
            name: 'photo.jpg',
        });

        upload(data).then(res => {
            Loading.show();
            //console.log(JSON.stringify((res)));
            const {url} = res;
            //上传成功后再新增记录
            const dataFace = {
                userId: userId,
                url: url,
            };
            saveFaceDatabase(dataFace).then(res => {
                Loading.hidden();
                goto('faceRecord', {title: '人脸录入'});
                //返回
            }).catch(err => {
                Loading.hidden();
                Toast.showWarning(err.toString());
            }).finally(() => {
                Loading.hidden();
            });

        }).catch(err => {
            console.log(JSON.stringify(err, 'ERR'));
            Toast.showWarning(err.toString());
        });

    };
    return device != null && hasPermission ? (
        <SafeAreaView edges={['top', 'left', 'right', 'bottom']} style={{flex: 1, backgroundColor: '#F1F0F5'}}>
            <View style={AllStyle.container}>
                <TouchableWithoutFeedback onPress={() => {
                    back();
                }}>
                    <Text style={{marginLeft: 15, fontSize: 18}}>
                        取消
                    </Text>
                </TouchableWithoutFeedback>
                <View style={{flex: 1, alignItems: 'center', marginTop: 20}}>
                    <View style={{
                        flexDirection: 'row',
                        justifyContent: 'center',
                        overflow: 'hidden',
                        position: 'relative',
                        alignItems: 'center',
                        width: 240,
                        height: 240,
                        borderRadius: 120,
                        borderWidth: 2,
                        borderColor: '#409EFF',
                    }}>
                        <Camera
                            ref={camara}
                            style={{width: faceWidthAndHeight, height: faceWidthAndHeight, borderRadius: 110}}
                            device={device}
                            //format={{format}}
                            isActive={isActiveVal}
                            photo={true}
                            frameProcessor={frameProcessor}
                            frameProcessorFps={'auto'}
                        />
                        <Text style={{
                            fontSize: 16,
                            color: '#fff',
                            fontWeight: '500',
                            position: 'absolute',
                            top: 195,
                            textAlign: 'center',
                        }}>{msg}</Text>
                        <View style={{
                            backgroundColor: '#000',
                            opacity: 0.1,
                            position: 'absolute',
                            width: 220,
                            top: 190,
                            height: 60,
                        }}>
                        </View>
                    </View>
                    <View style={{marginTop: 15}}>
                        <Text style={{fontSize: 20, fontWeight: '400'}}>{uploadMsg}</Text>
                    </View>
                </View>
                {/*<Image style={{height: 50, width: 50}}*/}
                {/*       //source={{uri:photoPath}}*/}
                {/*       source={{uri:`file://${photoPath}`}}*/}
                {/*/>*/}

                {uploadMsg == '上传成功' &&
                <View>
                    <TouchableOpacity style={{paddingTop: 10}} onPress={() => {
                        reEntry();
                    }}>

                        <Text style={{
                            borderWidth: 1, borderColor: '#BDC2C1', fontSize: 16, paddingTop: 10,
                            textAlign: 'center',
                            paddingBottom: 10, marginRight: 15, marginLeft: 15, borderRadius: 10, color: '#409EFF',
                        }}>重新录入</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{paddingTop: 10}} onPress={() => {
                        complete();
                    }}>
                        <View style={{borderRadius: 10, marginRight: 15, marginLeft: 15, backgroundColor: '#409EFF'}}>
                            <Text style={{
                                fontSize: 16, paddingTop: 10,
                                textAlign: 'center',
                                paddingBottom: 10, color: '#FFF',
                            }}>完成</Text>
                        </View>

                    </TouchableOpacity>

                </View>
                }

                {/*<TouchableOpacity onPress={()=>{*/}
                {/*    console.log(JSON.stringify(props));*/}
                {/*    goto('faceRecord',{title:'人脸录入'})*/}
                {/*}}>*/}
                {/*    <Text>查看props</Text>*/}
                {/*</TouchableOpacity>*/}


            </View>

        </SafeAreaView>
    ) : null;
}


// import * as React from 'react';
//
// import { StyleSheet, Text } from 'react-native';
// import { useCameraDevices } from 'react-native-vision-camera';
// import { Camera } from 'react-native-vision-camera';
// import { useScanBarcodes, BarcodeFormat } from 'vision-camera-code-scanner';
//
// export  function FaceDetection() {
//     const [hasPermission, setHasPermission] = React.useState(false);
//     const devices = useCameraDevices();
//     const device = devices.back;
//
//     const [frameProcessor, barcodes] = useScanBarcodes([BarcodeFormat.QR_CODE], {
//         checkInverted: true,
//     });
//
//     // Alternatively you can use the underlying function:
//     //
//     // const frameProcessor = useFrameProcessor((frame) => {
//     //   'worklet';
//     //   const detectedBarcodes = scanBarcodes(frame, [BarcodeFormat.QR_CODE], { checkInverted: true });
//     //   runOnJS(setBarcodes)(detectedBarcodes);
//     // }, []);
//
//     React.useEffect(() => {
//         (async () => {
//             const status = await Camera.requestCameraPermission();
//             setHasPermission(status === 'authorized');
//         })();
//     }, []);
//
//     return (
//         device != null &&
//         hasPermission && (
//             <>
//                 <Camera
//                     style={StyleSheet.absoluteFill}
//                     device={device}
//                     isActive={true}
//                     frameProcessor={frameProcessor}
//                     frameProcessorFps={5}
//                 />
//                 {barcodes.map((barcode, idx) => (
//                     <Text key={idx} style={styles.barcodeTextURL}>
//                         {barcode.displayValue}
//                     </Text>
//                 ))}
//             </>
//         )
//     );
// }
//
// const styles = StyleSheet.create({
//     barcodeTextURL: {
//         fontSize: 20,
//         color: 'white',
//         fontWeight: 'bold',
//     },
// });

